package cn.coin.ox.common.erc20.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.tx.Contract;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ExecutionException;

public class ERC20Util {

    private static Logger log = LoggerFactory.getLogger(ERC20Util.class);
    private static final BigDecimal WEI = new BigDecimal(1000000);

    public static final String TRANSFER = "transfer";

    /**
     * 获取ERC-20 token指定地址余额
     *
     * @param address         查询地址
     * @param contractAddress 合约地址
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static String getERC20Balance(Web3j web3j, String address, String contractAddress) throws ExecutionException, InterruptedException {
        String methodName = "balanceOf";
        List<Type> inputParameters = new ArrayList<>();
        List<TypeReference<?>> outputParameters = new ArrayList<>();
        Address fromAddress = new Address(address);
        inputParameters.add(fromAddress);

        TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {
        };
        outputParameters.add(typeReference);
        Function function = new Function(methodName, inputParameters, outputParameters);
        String data = FunctionEncoder.encode(function);
        Transaction transaction = Transaction.createEthCallTransaction(address, contractAddress, data);

        EthCall ethCall;
        BigDecimal balanceValue = BigDecimal.ZERO;
        try {
            ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
            List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
            String value = String.valueOf(results.get(0).getValue());
            balanceValue = new BigDecimal(value).divide(WEI, 6, RoundingMode.HALF_DOWN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return balanceValue.toString();
    }

    /****************交易*****************/
    /**
     *
     * @param from 转账账号
     * @param to 收账账号
     * @param amount 额度
     * @param credentials 转账账号私钥
     * @param contractAddress 合约地址
     * @return 交易hash 失败返回null
     */
    public static String transferERC20Token(Web3j web3j,
                                            String from,
                                            String to,
                                            BigInteger amount,
                                            Credentials credentials,
                                            String contractAddress) throws ExecutionException, InterruptedException {
        //加载转账所需的凭证，用私钥
        //获取nonce，交易笔数
        BigInteger nonce = getNonce(web3j, from);
        //get gasPrice  Gas Price就是你愿意为一个单位的Gas出多少ether，一般用Gwei作单位。
        // 19000000000
        BigInteger gasPrice = getGasPrice(web3j).divide(BigInteger.valueOf(20));
//        BigInteger gasLimit = BigInteger.valueOf(Constants.GAS_LIMIT);
        // Gas Limit就是一次交易中gas的可用上限
        BigInteger gasLimit = Contract.GAS_LIMIT;
        //以太坊的交易手续费为：TxFee = gas * gas Price，单位Gwei

        // amount 加上 gas price 和 gaslimit 的乘积然后和余额进行比较

        //创建RawTransaction交易对象
        Function function = tranFunction(to, amount);

        String encodedFunction = FunctionEncoder.encode(function);

        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                contractAddress, encodedFunction);

        //签名Transaction，这里要对交易做签名
        byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);

        String hexValue = Numeric.toHexString(signMessage);
        //发送交易
//        EthSendTransaction ethSendTransaction = sendTransaction(web3j, hexValue);
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        // DATA - 32字节，交易哈希，如果交易未生效则返回全0哈
        // 希。
        String hash = ethSendTransaction.getTransactionHash();
        if (hash != null){
            System.err.println("交易成功: "+hash);
            EthGetTransactionReceipt send = web3j.ethGetTransactionReceipt(hash).sendAsync().get();
            Optional<TransactionReceipt> transactionReceipt = send.getTransactionReceipt();
            if(transactionReceipt.isPresent()){
                TransactionReceipt receipt = transactionReceipt.get();
                System.out.println("transaction from " + receipt.getFrom() + ", to "+receipt.getTo()+", amount:" + receipt.getBlockNumber() +
                        ", gasUsed " + receipt.getGasUsed());
            }
            return hash;
        }else {
            System.err.println("交易出错: "+ethSendTransaction.getError().getMessage());
        }
        return null;
    }


    /**
     * erc20代币转账
     *
     * @param from            转账地址
     * @param to              收款地址
     * @param value           转账金额
     * @param privateKey      转账这私钥
     * @param contractAddress 代币合约地址
     * @return 交易哈希
     * @throws ExecutionException
     * @throws InterruptedException
     * @throws IOException
     */
    public static String transferERC20Token(Web3j web3j, String from, String to, BigInteger value,
                                            String privateKey, String contractAddress)
            throws ExecutionException, InterruptedException, IOException {

        //加载转账所需的凭证，用私钥
        Credentials credentials = Credentials.create(privateKey);
        //获取nonce，交易笔数
        BigInteger nonce;
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
        if (ethGetTransactionCount == null) {
            return null;
        }
        nonce = ethGetTransactionCount.getTransactionCount();
        //gasPrice和gasLimit 都可以手动设置
        BigInteger gasPrice;
        EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
        if (ethGasPrice == null) {
            return null;
        }
        gasPrice = ethGasPrice.getGasPrice();
        //BigInteger.valueOf(4300000L) 如果交易失败 很可能是手续费的设置问题
        BigInteger gasLimit = BigInteger.valueOf(60000L);
        //ERC20代币合约方法
        value = value.multiply(WEI.toBigInteger());
        Function function = new Function(
                TRANSFER,
                Arrays.asList(new Address(to), new Uint256(value)),
                Collections.singletonList(new TypeReference<Type>() {
                }));
        //创建RawTransaction交易对象
        String encodedFunction = FunctionEncoder.encode(function);
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                contractAddress, encodedFunction);

        //签名Transaction
        byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signMessage);
        //发送交易
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        String hash = ethSendTransaction.getTransactionHash();
        if (hash != null) {
            log.info("交易成功: " + hash);
            return hash;
        }
        return null;
    }



    /**
     * 获取gas
     * @return BigInteger 当前gas
     */
    public static BigInteger getGasPrice(Web3j web3j) {
        BigInteger gas = null;
        try {
            EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
            if (ethGasPrice != null){
                gas = ethGasPrice.getGasPrice();
            }
        } catch (InterruptedException | ExecutionException e) {
            log.error("Web3j --> ethGasPrice:" + e.getCause().getMessage());
        }
        return gas;
    }

    /**
     * 获取nonce
     * @param from 转账地址
     * @return BigInteger类型nonce
     */
    public static BigInteger getNonce(Web3j web3j, String from) {
        EthGetTransactionCount transactionCount;
        BigInteger nonce = null;
        try {
            transactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.LATEST).sendAsync().get();
            nonce = transactionCount.getTransactionCount();
        } catch (InterruptedException | ExecutionException e) {
            log.error("获取nonce ：Web3j --> ethGetTransactionCount: " + e.getCause().getMessage());
        }
        return nonce;
    }

    /**
     * 合约方法
     * @param to 收账地址
     * @param value 转账额
     * @return Function
     */
    private static Function tranFunction(String to, BigInteger value) {
        Function function = null;
        try {
            function = new Function(
                    TRANSFER,
                    Arrays.asList(new Address(to), new Uint256(value)),
                    Collections.singletonList(new TypeReference<Type>() {
                    }));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return function;
    }

}
